package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.Code;
import com.itheima.common.MessageConstant;
import com.itheima.entity.Category;
import com.itheima.entity.Dish;
import com.itheima.entity.Setmeal;
import com.itheima.exception.BusinessException;
import com.itheima.mapper.CategoryMapper;
import com.itheima.mapper.DishMapper;
import com.itheima.mapper.SetmealMapper;
import com.itheima.service.CategoryService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
*@author: lzl
*@description: 菜品、套餐分类管理-业务实现类
*@date:Acer
*/
@Service
public class CategoryServiceImpl implements CategoryService {
    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private SetmealMapper setmealMapper;
    @Autowired
    private DishMapper dishMapper;


    /**
     * 页面分页展示 分页查询
     *
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public Page<Category> page(Integer page, Integer pageSize) {
        //校验和判断
        if (page < 1) {
            page = 1;
        }
        if (pageSize < 1) {
            pageSize = 1;
        }
        //2、构建分页条件、查询条件 new Page注入page和pageSize
        Page<Category> categoryPage = new Page<>(page, pageSize);
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByDesc(Category::getUpdateTime);
        wrapper.orderByAsc(Category::getSort);
        //3、执行查询
        Page<Category> pageResult = categoryMapper.selectPage(categoryPage, wrapper);
        return pageResult;
    }

    /**
     * 获取菜品分类列表数据
     * >>>>>>> Stashed changes
     *
     * @param type
     * @return
     */
    @Override
    public List<Category> findAll(Integer type) {
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
        //如果类型不为空 new Lam然后eq查询
        if (type != null) {
            wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Category::getType, type);
        }
        //根据sort字段升序降序
        wrapper.select(Category::getId, Category::getName, Category::getType);
        wrapper.orderByAsc(Category::getSort);
        wrapper.orderByDesc(Category::getUpdateTime);
        List<Category> categoryList = categoryMapper.selectList(wrapper);
        return categoryList;
    }


    /**
     * 新增菜品或者套餐分类
     *
     * @param category
     * @return
     */

    @Override
    public int save(Category category) {
        int row = 0;
        //1.校验参数
        if (category == null) {
            return row;
        }
        String name = category.getName();
        //判断分类名字的长度
        if (name.length() > 20) {
            return row;
        }
        //判断排序是否符合规范
        Integer sort = category.getSort();
        if (sort < 1 && sort > 999) {
            return row;
        }
        Integer type = category.getType();
        if (!(type == 1 || type == 2)) {
            return row;
        }
        char[] chars = name.toCharArray();
        for (char aChar : chars) {
            int a = aChar;
            if (a>=0&&a<256){
                throw new BusinessException(Code.ERROR,"菜品分类只能输入中文");
            }
        }

        //2.判断修改后的“分类名称”是否已经存在，如果已经存在则返回“分类名称已经存在，请重新输入分类名称”友好错误提示
        //根据前端传递过来的【name】,判断数据库是否有名称一致的分类
        if (StringUtils.isNotBlank(name)) {
            LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Category::getName, name);
            Category one = categoryMapper.selectOne(wrapper);
            // 2.1）如果名称一致，但是ID不一致，说明我们把分类名称改成了一个已经存在的分类名称----不允许修改
            if (one != null) {
                    throw new BusinessException(Code.ERROR,MessageConstant.CAT_NAME_IS_EXIST);
            }
        }

        row = categoryMapper.insert(category);
        return row;


    }

    /**
     * 根据id删除套餐分类或者菜品分类
     *
     * @param id
     * @return
     */
    @Override
    public int deleteById(Long id) {
        int row = 0;
        //1.校验参数
        if (id == null) {
            return row;
        }
        //2.判断该分类下是否有菜品、套餐，
        //查询菜品与分类id相关联的菜品
        LambdaQueryWrapper<Dish> dishwrapper = new LambdaQueryWrapper<>();
        dishwrapper.eq(Dish::getCategoryId, id);
        List<Dish> dishes = dishMapper.selectList(dishwrapper);
        if (dishes.size() != 0) {
            throw new BusinessException(Code.ERROR,"菜品分类中有菜品无法删除");

        }
        //查询套餐与分类id相关联的套餐
        LambdaQueryWrapper<Setmeal> setmealWrapper = new LambdaQueryWrapper<>();
        setmealWrapper.eq(Setmeal::getCategoryId, id);
        Setmeal setmeal = setmealMapper.selectOne(setmealWrapper);
        if (setmeal != null) {
            throw new BusinessException(Code.ERROR,"套餐中有菜品无法删除");
        }
        //2.1如果有的话不允许删除
        //2.2 分类下没有的话可以删除
        row = categoryMapper.deleteById(id);
        return row;
    }

    /**
     * 更新分类信息
     *
     * @param category
     * @return
     */
    @Override
    public int update(Category category) {
        int row = 0;
        //校验参数
        if (category == null) {
            return row;
        }
        //判断修改后的“分类名称”是否已经存在，如果已经存在则返回“分类名称已经存在，请重新输入分类名称”友好错误提示
        String name = category.getName();

        Integer sort = category.getSort();
        //根据name 和前端传过来的name 判断数据库是否有一样的分类名字
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Category::getName, name);

        Category one = categoryMapper.selectOne(wrapper);
        if (one != null) {
            Long id = one.getId();
            Long categoryId = category.getId();
            if (id.equals(categoryId)) {
                row = categoryMapper.updateById(category);
            }
        }
        if (one != null) {
            Integer oneSort = one.getSort();
            Integer categorySort = category.getSort();
            if (oneSort.equals(categorySort)) {
                row = categoryMapper.updateById(category);
            }
        }
        char[] chars = name.toCharArray();
        for (char aChar : chars) {
            int a = aChar;
            if (a>=0&&a<256){
                throw new BusinessException(Code.ERROR,"菜品分类只能输入中文");
            }
        }
        //如果名称一致，但是ID不一致，说明我们把分类名称改成了一个已经存在的分类名称----不允许修改
           if (one != null && !category.getId().equals(one.getId())) {
               throw new BusinessException(Code.ERROR,MessageConstant.CAT_NAME_IS_EXIST);
          }
            row = categoryMapper.updateById(category);
            return row;
        }
    }



